<template>
  <div class="table-search-view-wrapper">
    <!--搜索区域-->
    <div v-if="searchItems.length>0" class="search-form-wrapper">
      <el-form class="search-form" :inline="true" :model="model" ref="searchForm" label-width="9em">
        <el-form-item v-for="(item,index) in searchItems" :key="index" :label="item.label">
          <!--带建议的输入框-->
          <template v-if="item.type==='autocomplete'">
            <el-autocomplete
                v-model="model[item.model]"
                :fetch-suggestions="fetchSuggestions"
                :placeholder="item.placeholder"
                :trigger-on-focus="false"
                style="width: 325px;">
            </el-autocomplete>
          </template>

          <!--日期范围选择器-->
          <template v-if="item.type==='datetimerange'">
            <el-date-picker
                v-model="model[item.model]"
                type="datetimerange"
                :picker-options="pickerOptions"
                :placeholder="item.placeholder" style="width: 325px;">
            </el-date-picker>
          </template>

          <!--input输入框-->
          <template v-if="item.type==='input'">
            <el-input
                v-model="model[item.model]"
                :placeholder="item.placeholder"
                style="width: 325px;">
            </el-input>
          </template>

          <!--input number-->
          <template v-if="item.type==='number'">
            <el-input
                v-model.number="model[item.model]"
                :placeholder="item.placeholder"
                style="width: 325px;">
            </el-input>
          </template>

          <!--下拉框-->
          <template v-if="item.type==='select'">
            <el-select v-model="model[item.model]"
               :multiple="!!item.multiple"
               :filterable="!!item.filterable"
               :clearable="!!item.clearable"
               :placeholder="item.placeholder"
               style="width: 325px;">
              <el-option
                  v-for="option in item.options"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value">
              </el-option>
            </el-select>
          </template>

        </el-form-item>

        <div class="search-form-btn-wrapper">
          <el-form-item>
            <el-button type="primary" @click="search()">搜索</el-button>
            <el-button @click="resetForm('searchForm')">重置</el-button>
          </el-form-item>
        </div>

      </el-form>
    </div>

    <!--列表区域-->
    <div class="result-data-wrapper" v-loading="loading">
      <template v-if="!data.length">
        <empty>{{emptyText}}</empty>
      </template>
      <template v-if="data.length">
        <el-table :data="data">
          <template v-for="(item, index) in tableItems">
            <!--多选-->
            <el-table-column v-if="item.type === 'selection'"
                type="selection"
                width="55">
            </el-table-column>
            <!--自定义,需要指定slot-->
            <el-table-column v-if="item.type === 'scope'"
               :label="item.label"
               :width="item.width"
               :class-name="item.className">
              <template slot-scope="scope">
                <slot :name="item.slot" :index="scope.$index" :row="scope.row" :rows="data"></slot>
              </template>
            </el-table-column>
            <!--通常-->
            <el-table-column v-if="!item.type"
               :label="item.label"
               :prop="item.prop"
               :formatter="item.formatter?formatter[item.formatter]:null"
               :sortable="!!item.sortable"
               :width="item.width"
               :class-name="item.className">
            </el-table-column>

          </template>
        </el-table>

        <!--分页-->
        <div class="pagination-wrapper">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-size="pageSize"
              :page-sizes="[5, 10, 20, 30, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </div>
      </template>
    </div>

  </div>
</template>

<script>
  import Empty from '@/components/Empty';
  import {parseTime,parsePrice} from '@/common/filters';

  export default {
    name: 'tableSearchView',
    components: {
      'empty': Empty,
    },
    props: {
      emptyText: {
        type: String,
        default: '没有搜索到任何数据',
      },
      searchItems: { //需要哪些搜索组件,label:表单名, type表单类型,model:表单value存放在data的键值,字段对应api请求体, placeholder,
        type: Array,
        default: () => [], //{label, type, model,placeholder}
      },
      tableItems: {  //表格需要展示的内容,label:th名,prop:对应返回api json响应字段, sortable 是否排序,详细见代码
        type: Array,
        default: () => [],//{label, prop, sortable}
      },
      searchFunction: {
        type: Function,
        default: (data) => {
          return Promise.reject();
        },
      },
    },
    data()
    {
      return {
        loading: false,
        model: {transactionType:[]}, //存储表单数据, 多选属性需要初始化数组，elementui的坑。。
        data: [], //数据集
        pageSize: 10,
        currentPage: 1,
        total: 0,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker)
            {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker)
            {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker)
            {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        formatter:{
          'parseTime': (row,column,cellValue) => parseTime(cellValue),
          'parsePrice': (row,column,cellValue) => parsePrice(cellValue),
        },
        completeList: [ //自动完成的数据
          /*{"value": "iPhone5"},
          {"value": "iPhone5s"},
          {"value": "iPhone6"},
          {"value": "iPhone6 Plus"},
          {"value": "iPhone6s"},
          {"value": "iPhone6s Plus"},
          {"value": "iPhone7"},
          {"value": "iPhone7 Plus"},
          {"value": "iPhone8 Plus"},
          {"value": "iPhone X"},
          {"value": "iPhone SE"},*/
        ],
      }
    },
    mounted()
    {

    },
    methods: {
      fetchSuggestions(queryString, cb) //输入弹出自动完成列表
      {
        let hit = this.completeList.filter((item) => {
          return item.value.toString().toLowerCase().indexOf(queryString.toLowerCase()) !== -1;
        });
        cb(hit);
      },
      getRequestDate() //请求参数
      {
        let request = {};
        this.searchItems.forEach((item) => {
          let value = this.model[item.model];
          if (value)
          {
            if (item.type === 'datetimerange')
            {
              let startTime = value[0]; //查询的开始时间
              let endTime = value[1]; //查询的结束时间

              if (startTime)
              {
                let key = item.start || 'startTime';
                request[key] = new Date(startTime).getTime();
              }
              if (endTime)
              {
                let key = item.end || 'endTime';
                request[key] = new Date(endTime).getTime();
              }
            }
            else if(item.type === 'select' && item.multiple && value.length > 0)
            {
              request[item.model] = value;
            }
            else
            {
              request[item.model] = value;
            }
          }
        });

        request.pageSize = this.pageSize;
        request.pageNum = this.currentPage;
        return request;
      },
      search() //执行搜索
      {
        this.loading = true;
        let data = this.getRequestDate();

        this.searchFunction(data).then(
          (resp) => {
            this.data = resp.data.list || [];
            this.total = resp.data.total || 0;

            setTimeout(()=>{
              this.loading = false;
            },300);

          }).catch((err) => {

          setTimeout(()=>{
            this.loading = false;
          },300);

        });

      },
      resetForm(formName)
      {
        this.model = {};
        //this.$refs[formName].resetFields();
      },
      handleSizeChange(val) //分页pageSize变动
      {
        this.pageSize = val;
        this.search();
      },
      handleCurrentChange(val) //currentPage变动
      {
        this.currentPage = val;
        this.search();
      },
      formatterTime(row, column, cellValue) //格式化输出时间
      {
        if (!isNaN(cellValue))
        {
          return parseTime(cellValue);
        }

        return cellValue;
      },
    },
    mounted()
    {
      this.search();
    }
  }
</script>

<style lang="scss">
  .table-search-view-wrapper {
    .search-form-wrapper {
      width: 960px;
      .search-form {
        .search-form-btn-wrapper {
          display: block;
          text-align: center;
          margin-top: 20px;

          .el-button {
            margin-left: 40px;
          }

        }
      }
    }
    .result-data-wrapper {
      margin-top: 20px;
      .el-table .cell
      {
        padding: 0 10px;
      }
    }
    .pagination-wrapper {
      display: block;
      text-align: center;
      margin: 30px 0;
    }
  }
</style>
